# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.contrib.localflavor.ar.forms import ARDNIField, ARCUITField

from gente.utils import generate_id
from gente.models import Cliente, Empleado


ARDNIField.default_error_messages = {
    'invalid': 'Sólo valores numéricos',
    'max_digits': 'Sólo se requieren 7 u 8 dígitos'}
ARCUITField.default_error_messages = {
    'invalid': 'Utilice formato de CUIT XX-XXXXXXXX-X o XXXXXXXXXXXX (sólo valores numéricos)',
    'checksum': 'CUIT inválido'}


class EmpleadoAdminForm(forms.ModelForm):
    apellido = forms.CharField(max_length=30)
    nombre = forms.CharField(max_length=30)
    dni = ARDNIField(max_length=8)
    email = forms.EmailField(max_length=75)

    class Meta:
        model = Empleado

    def __init__(self, *args, **kwargs):
        empleado = kwargs.get('instance')
        initial = kwargs.get('initial', {})
        if empleado is not None:
            initial.update({
                'apellido': empleado.apellido,
                'nombre': empleado.nombre,
                'email': empleado.email})
            kwargs['initial'] = initial
        super(EmpleadoAdminForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        nombre = self.cleaned_data['nombre']
        apellido = self.cleaned_data['apellido']
        email = self.cleaned_data['email']
        dni = self.cleaned_data['dni']
        if self.instance.pk is None:
            user = User(username=generate_id(nombre, apellido, email, dni))
        else:
            user = self.instance.user
        user.first_name = nombre
        user.last_name = apellido
        user.email = email
        user.set_unusable_password()
        user.save()
        empleado = super(EmpleadoAdminForm, self).save(commit=False)
        empleado.user = user
        if commit:
            empleado.save()
        return empleado


class ClienteAdminForm(forms.ModelForm):
    dni = ARDNIField(max_length=8)
    cuit_o_cuil = ARCUITField(required=False)

    class Meta:
        model = Cliente
